<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      :defaults.sync="defaults"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template slot="menuRight">
        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>
      </template>
      <template slot="menuLeft">
        <el-button type="primary" size="small" icon="el-icon-plus" v-if="permission.inventoryManage_add" @click="addBtn">新 增</el-button>
        <el-button size="small" icon="el-icon-check" @click="enable" v-if="permission.inventoryManage_use">启 用</el-button>
        <el-button size="small" icon="el-icon-circle-close" @click="cancel" v-if="permission.inventoryManage_cancel">取 消</el-button>
        <el-button type="warning" size="small" icon="el-icon-download" @click="$refs.exportComp.visible = true">导出</el-button>
      </template>
      <template slot-scope="{ row }" slot="menu">
        <el-button icon="el-icon-view" size="small" type="text" @click="rowView(row)" v-if="permission.inventoryManage_view">详情</el-button>
        <el-button icon="el-icon-edit" size="small" type="text" @click="rowUpdate(row)" :disabled="row.status != 1 ? true : false" v-if="permission.inventoryManage_edit"
          >编辑</el-button
        >
        <el-button
          icon="el-icon-circle-check"
          size="small"
          type="text"
          @click.stop="complete(row)"
          :disabled="row.status != 3 ? true : false"
          v-if="permission.inventoryManage_finish"
          >完成</el-button
        >
        <el-button
          icon="el-icon-printer"
          size="small"
          type="text"
          @click.stop="showPrint(row)"
          :disabled="row.status != 4 ? true : false"
          v-if="permission.inventoryManage_print"
          >打印</el-button
        >
      </template>
    </avue-crud>
    <el-dialog
      class="inventoryDialog"
      v-dragDirectives
      ref="dialog"
      :title="dialogTitle"
      append-to-body
      :visible.sync="showDialog"
      :close-on-click-modal="false"
      top="5vh"
      @close="closeDialog"
    >
      <avue-form ref="basicInfo" v-if="showDialog" v-model="form" :option="dialogTitle === '新增' || dialogTitle === '编辑' ? addDialogOption : viewDialogOption"></avue-form>
      <div v-if="dialogTitle === '新增' || dialogTitle === '编辑'">
        <h3><i class="el-icon-vertical-bar mr10"></i>物料盘点列表</h3>
        <div style="margin-bottom: 20px">
          <el-button v-if="dialogTitle === '新增' || dialogTitle === '编辑'" size="small" @click="openAreaStash" type="primary">指定仓库</el-button>
          <el-button v-if="dialogTitle === '新增' || dialogTitle === '编辑'" size="small" @click="openAreaSelect" type="primary">指定区域</el-button>
          <el-button v-if="dialogTitle === '新增' || dialogTitle === '编辑'" size="small" @click="openPartSelect" type="primary">指定物料</el-button>
          <el-button v-if="dialogTitle === '新增' || dialogTitle === '编辑'" type="danger" size="small" icon="el-icon-delete" @click="deletePart">删 除 </el-button>
        </div>
      </div>
      <div v-if="dialogTitle === '详情'">
        <h3><i class="el-icon-vertical-bar mr10"></i>盘点明细</h3>
      </div>
      <avue-crud
        v-if="dialogTitle === '新增' || dialogTitle === '编辑'"
        :option="partOption"
        :table-loading="loading"
        :data="partList"
        ref="partCrud"
        @selection-change="selectionPartChange"
      ></avue-crud>
      <span v-if="dialogTitle === '新增' || dialogTitle === '编辑'" slot="footer" class="dialog-footer">
        <el-button v-if="dialogTitle === '新增'" type="primary" size="small" @click="submit" :disabled="planSaveLoading"
          ><i class="el-icon-circle-plus-outline"></i><span>保 存</span></el-button
        >
        <el-button v-if="dialogTitle === '编辑'" type="primary" size="small" @click="submit" :disabled="planSaveLoading"
          ><i class="el-icon-circle-check"></i><span>修 改</span></el-button
        >
        <el-button size="small" @click="showDialog = false"><i class="el-icon-circle-close"></i><span>取 消</span></el-button>
      </span>
      <avue-crud v-if="dialogTitle === '详情'" :page.sync="checkMaterialPage" :option="checkMaterialOption" :table-loading="checkMaterialLoading" :data="checkMaterialList">
        <template slot-scope="{ row }" slot="menu">
          <el-button icon="el-icon-view" size="small" type="text" @click="viewPackInfo(row)">查看包装</el-button>
        </template>
      </avue-crud>
    </el-dialog>
    <el-dialog v-dragDirectives ref="dialog" title="指定区域" append-to-body :visible.sync="selectAreaDialog" :close-on-click-modal="false" @close="closeAreaDialog" width="30%">
      <avue-form ref="areaInfo" v-if="selectAreaDialog" v-model="areaList" :option="areaOption"></avue-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" @click="saveArea" :disabled="savaAreaLoading"><i class="el-icon-circle-plus-outline"></i><span>保 存</span></el-button>
        <el-button size="small" @click="selectAreaDialog = false"><i class="el-icon-circle-close"></i><span>取 消</span></el-button>
      </span>
    </el-dialog>
    <el-dialog v-dragDirectives ref="dialog" title="打印" append-to-body :visible.sync="printDialog" :close-on-click-modal="false" @close="closePrintDialog" width="30%">
      <common-printers-template ref="printInfo" :labelWidth="100" @getPrintInfo="getPrintInfo"></common-printers-template>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" @click="submitPrint" :disabled="savePrintLoading"><i class="el-icon-circle-plus-outline"></i><span>提 交</span></el-button>
        <el-button size="small" @click="printDialog = false"><i class="el-icon-circle-close"></i><span>取 消</span></el-button>
      </span>
    </el-dialog>
    <export-comp ref="exportComp" page-api-url="" reportCode="materialPlan_export" :option="option" :page="page" :query="query" file-name="仓库盘点"> </export-comp>
    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"> </common-modal-template>
  </basic-container>
</template>
<script>
import {
  getList,
  add,
  getPartByArea,
  getCheckMaterialList,
  getCheckMaterialPage,
  checkCancel,
  checkCompleted,
  checkEnable,
  checkPrint,
  getInventoryInfo,
  getSubTypeList
} from '@/api/warehouse/inventory-manage';
import { mapGetters } from 'vuex';
import exportComp from '@/components/export-comp';
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
import CommonPrintersTemplate from '@/components/common-printers-template/common-printers-template.vue';
import userTableConfig from '@/components/user-table-config/index.vue';
import userConfig from '@/mixins/userConfig';
export default {
  name: 'WarehouseInventoryManage',
  components: {
    CommonModalTemplate,
    CommonPrintersTemplate,
    userTableConfig,
    exportComp
  },
  mixins: [userConfig()],
  data() {
    return {
      pageCode: 'INVERTORY_MANAGE',
      form: {},
      defaults: {},
      query: {},
      loading: true,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {
        height: 'calc(100vh - 482px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 16,
        searchMenuPosition: 'right',
        border: true,
        index: true,
        indexLabel: '序号',
        addBtn: false,
        viewBtn: false,
        editBtn: false,
        delBtn: false,
        selection: true,
        menuWidth: 250, //弹框内字段宽度属性
        dialogWidth: 880, //弹框宽度属性
        labelWidth: '110',
        dialogClickModal: false,
        columnBtn: false,
        column: [
          {
            label: '盘点单号',
            prop: 'planNo',
            search: true,
            searchSpan: 4
          },
          {
            label: '单据名称',
            prop: 'planName',
            search: true,
            searchSpan: 4
          },
          {
            label: '状态',
            prop: 'status',
            search: true,
            searchSpan: 4,
            type: 'select',
            dicUrl: '/api/blade-system/dict/dictionary?code=check_status',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            }
          },
          {
            label: '物料数量',
            prop: 'partMasterCount'
          },
          {
            label: '盘点类型',
            prop: 'planSubType',
            type: 'select',
            dicUrl: '/api/blade-system/dict/dictionary?code=plan_sub_type',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            }
          },
          {
            label: '关联单据',
            prop: 'referencePlanNo'
          },
          {
            label: '计划来源',
            prop: 'planSource',
            type: 'select',
            search: true,
            searchSpan: 4,
            dicData: [
              {
                label: 'ERP同步',
                value: 'ERP'
              },
              {
                label: 'MES发起',
                value: 'MES'
              }
            ]
          },
          {
            label: '是否启用',
            prop: 'isEnabled',
            type: 'switch',
            value: true,
            dicData: [
              {
                label: '否',
                value: false
              },
              {
                label: '是',
                value: true
              }
            ]
          },
          {
            label: '开始日期',
            prop: 'planStartTime'
          },
          {
            label: '结束日期',
            prop: 'planEndTime'
          },
          {
            label: '创建时间',
            prop: 'createTime'
          },
          {
            label: '开始日期',
            prop: 'checkingStartDate',
            searchType: 'datetimerange',
            format: 'yyyy-MM-dd HH:mm:ss',
            valueFormat: 'yyyy-MM-dd HH:mm:ss',
            startPlaceholder: '计划开始日期',
            endPlaceholder: '计划开始日期',
            searchSpan: 8,
            search: true,
            display: false,
            hide: true
          },
          {
            label: '结束日期',
            prop: 'checkingEndDate',
            searchType: 'datetimerange',
            format: 'yyyy-MM-dd HH:mm:ss',
            valueFormat: 'yyyy-MM-dd HH:mm:ss',
            startPlaceholder: '计划结束日期',
            endPlaceholder: '计划结束日期',
            searchSpan: 8,
            search: true,
            display: false,
            hide: true
          }
        ]
      },
      dialogTitle: '新增',
      showDialog: false,
      addDialogOption: {
        submitBtn: false,
        emptyBtn: false,
        // labelWidth: '100',
        column: [
          {
            label: '计划名称',
            prop: 'planName',
            rules: [
              {
                required: true,
                message: '请输入计划名称',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '盘点日期',
            prop: 'checkDate',
            type: 'datetimerange',
            format: 'yyyy-MM-dd HH:mm:ss',
            valueFormat: 'yyyy-MM-dd HH:mm:ss',
            startPlaceholder: '盘点开始日期',
            endPlaceholder: '盘点结束日期',
            rules: [
              {
                required: true,
                message: '请选择盘点日期',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '盘点人员',
            prop: 'operatorsName',
            type: 'search',
            disabled: true,
            appendClick: () => {
              this.openPrincipalCommonModal();
            },
            rules: [
              {
                required: true,
                message: '请选择盘点人员',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '盘点类型',
            prop: 'planSubType',
            type: 'select',
            dicUrl: '/api/blade-system/dict/dictionary?code=plan_sub_type',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            control: (val, form) => {
              if (form.planSubType == 'CHECK') {
                return {
                  referencePlanNo: {
                    display: false
                  }
                };
              } else if (form.planSubType == 'RECHECK') {
                return {
                  referencePlanNo: {
                    display: true
                  }
                };
              }
            },
            rules: [
              {
                required: true,
                message: '请选择盘点类型',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '关联单据',
            prop: 'referencePlanNo',
            type: 'search',
            display: false,
            appendClick: () => {
              this.openSheetheaderCommonModal();
            },
            rules: [
              {
                required: true,
                message: '请选择关联单据',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '备注',
            prop: 'description',
            hide: true,
            type: 'textarea',
            maxlength: 150,
            showWordLimit: true
          }
        ]
      },
      viewDialogOption: {
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: '计划名称',
            prop: 'planName',
            disabled: true
          },
          {
            label: '计划编码',
            prop: 'planNo',
            disabled: true
          },
          {
            label: '盘点类型',
            prop: 'planSubType',
            type: 'select',
            dicUrl: '/api/blade-system/dict/dictionary?code=plan_sub_type',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            disabled: true
          },
          {
            label: '关联单据',
            prop: 'referencePlanNo',
            disabled: true
          },
          {
            label: '计划来源',
            prop: 'planSource',
            type: 'select',
            disabled: true,
            dicData: [
              {
                label: 'ERP同步',
                value: 'ERP'
              },
              {
                label: 'MES发起',
                value: 'MES'
              }
            ]
          },
          {
            label: '创建人员',
            prop: 'createUserName',
            disabled: true
          },
          {
            label: '创建日期',
            prop: 'createTime',
            disabled: true
          },
          {
            label: '盘点日期',
            prop: 'checkDate',
            type: 'datetimerange',
            format: 'yyyy-MM-dd HH:mm:ss',
            valueFormat: 'yyyy-MM-dd HH:mm:ss',
            disabled: true
          },
          {
            label: '盘点人员',
            prop: 'operatorsName',
            disabled: true
          },
          {
            label: '备注',
            prop: 'description',
            hide: true,
            type: 'textarea',
            maxlength: 150,
            showWordLimit: true
          }
        ]
      },
      partOption: {
        height: '350',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 4,
        border: true,
        index: true,
        indexLabel: '序号',
        addBtn: false,
        viewBtn: false,
        editBtn: false,
        delBtn: false,
        selection: true,
        labelWidth: '110',
        dialogClickModal: false,
        menu: false,
        refreshBtn: false,
        columnBtn: false,
        rowKey: 'keyJson',
        column: [
          {
            label: '库存中心',
            prop: 'inventoryName'
          },
          {
            label: '储位编码',
            prop: 'areaCode'
          },
          {
            label: '储位名称',
            prop: 'areaName'
          },
          {
            label: '编码',
            prop: 'partNo'
          },
          {
            label: '名称',
            prop: 'partMasterName'
          },
          {
            label: '型号',
            prop: 'partModel'
          },
          {
            label: '单位',
            prop: 'uom'
          },
          {
            label: '类型',
            prop: 'partType',
            dicData: [
              { label: '成品', value: 'PRODUCT' },
              { label: '原料', value: 'MATERIAL' }
            ]
          },
          {
            label: '物料批次',
            prop: 'lotNo'
          },
          {
            label: '账面数量',
            prop: 'inventoryQuantity'
          }
        ]
      },
      checkMaterialPage: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      checkMaterialLoading: false,
      checkMaterialOption: {
        height: '350',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 4,
        border: true,
        index: true,
        indexLabel: '序号',
        addBtn: false,
        viewBtn: false,
        editBtn: false,
        delBtn: false,
        selection: false,
        dialogClickModal: false,
        refreshBtn: false,
        columnBtn: false,
        menuWidth: 100,
        column: [
          {
            label: '库存中心',
            prop: 'inventoryName'
          },
          {
            label: '储位编码',
            prop: 'areaCode'
          },
          {
            label: '储位名称',
            prop: 'areaName'
          },
          {
            label: '编码',
            prop: 'partNo'
          },
          {
            label: '名称',
            prop: 'partMasterName'
          },
          {
            label: '型号',
            prop: 'partModel'
          },
          {
            label: '单位',
            prop: 'uom'
          },
          {
            label: '账面数量',
            prop: 'inventoryQuantity'
          },
          {
            label: '实盘数量',
            prop: 'checkQuantity'
          },
          {
            label: '盈亏数量',
            prop: 'difference',
            html: true,
            formatter: (val) => {
              if (Number(val.difference) < 0) {
                return '<span class="text-green">' + val.difference + '</span>';
              } else if (Number(val.difference) > 0) {
                return '<span class="text-red">' + val.difference + '</span>';
              } else {
                return val.difference;
              }
            }
          },
          {
            label: '状态',
            prop: 'status',
            type: 'select',
            dicUrl: '/api/blade-system/dict/dictionary?code=check_status',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            formatter: (val) => {
              switch (val.status) {
                case 1:
                  return '待执行';
                case 2:
                  return '盘点中';
                case 3:
                  return '待审核';
                case 4:
                  return '已审核';
                case 5:
                  return '已取消';
              }
            }
          }
        ]
      },
      checkMaterialList: [],
      timer: new Date().getTime(), //不同内容使用同一个模态框结构，key值不同需要重新请求渲染数据，否则会请求到上一个使用的数据内容
      modalName: '', //打开公用模态框名称
      tableOption: {}, //公用模态框配置信息,
      partList: [],
      selectionPartList: [],
      selectAreaDialog: false,
      areaOption: {
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: '区域',
            prop: 'areaName',
            span: 24,
            type: 'tree',
            multiple: true,
            filterable: true,
            dicUrl: '/api/mes-admin/area/select/storage/management?level=2&areaType=STORAGE_AREA',
            props: {
              label: 'name',
              value: 'id'
            },
            checked: (item, data) => {
              this.selectAreaList = data.checkedNodes;
            },
            rules: [
              {
                required: true,
                message: '请选择区域',
                trigger: 'blur'
              }
            ]
          }
        ]
      },
      areaList: [],
      selectAreaList: [],
      printDialog: false,
      printInfo: {},
      selectPrintPlanId: '',
      planSaveLoading: false, //计划保存防重提交
      savaAreaLoading: false, //保存选择储位防重提交
      savePrintLoading: false //打印防重提交
    };
  },
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
    });
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.inventoryManage_add, false),
        viewBtn: this.vaildData(this.permission.inventoryManage_view, false),
        delBtn: this.vaildData(this.permission.inventoryManage_delete, false),
        editBtn: this.vaildData(this.permission.inventoryManage_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    },
    partIds() {
      let ids = [];
      this.selectionPartList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids;
    }
  },
  methods: {
    /**
     * 重新加载公用表格弹窗组件
     */
    newKey() {
      this.timer = new Date().getTime();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      if (this.query.checkingStartDate) {
        this.query.planStartTimeStart = this.query.checkingStartDate[0];
        this.query.planStartTimeEnd = this.query.checkingStartDate[1];
        delete this.query.checkingStartDate;
      }
      if (this.query.checkingEndDate) {
        this.query.planEndTimeStart = this.query.checkingEndDate[0];
        this.query.planEndTimeEnd = this.query.checkingEndDate[1];
        delete this.query.checkingEndDate;
      }
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this._forEach(this.data, (item) => {
          item.status = String(item.status);
        });
        this.loading = false;
        this.selectionClear();
      });
    },
    addBtn() {
      this.showDialog = true;
      this.dialogTitle = '新增';
    },
    openPrincipalCommonModal() {
      this.modalName = 'principalModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择用户信息',
        url: '/api/blade-system/user/page',
        isPage: true,
        rowSelectionType: 'multiple',
        columnDefs: [
          {
            label: '用户姓名',
            prop: 'realName',
            search: true,
            searchLabelWidth: 150,
            searchSpan: 8
          },
          {
            label: '所属部门',
            prop: 'deptName',
            searchLabelWidth: 150,
            searchSpan: 8
          },
          {
            label: '职务',
            prop: 'postName'
          },
          {
            label: '用户平台',
            prop: 'userTypeName'
          }
        ]
      };
    },
    openSheetheaderCommonModal() {
      this.modalName = 'referencePlanNoModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择单据信息（双击进行选择）',
        url: '/api/mes-warehouse/checking/page?planSubType=CHECK',
        isPage: true,
        rowSelectionType: 'single',
        searchMenuSpan: 24,
        columnDefs: [
          {
            label: '盘点单号',
            prop: 'planNo',
            search: true
          },
          {
            label: '单据名称',
            prop: 'planName',
            search: true
          },
          {
            label: '状态',
            prop: 'status',
            search: true,
            type: 'select',
            dicUrl: '/api/blade-system/dict/dictionary?code=check_status',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            }
          },
          {
            label: '物料数量',
            prop: 'partMasterCount'
          },
          {
            label: '盘点类型',
            prop: 'planSubType',
            type: 'select',
            dicUrl: '/api/blade-system/dict/dictionary?code=plan_sub_type',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            }
          },
          {
            label: '关联单据',
            prop: 'referencePlanNo'
          },
          {
            label: '计划来源',
            prop: 'planSource',
            type: 'select',
            search: true,
            dicData: [
              {
                label: 'ERP同步',
                value: 'ERP'
              },
              {
                label: 'MES发起',
                value: 'MES'
              }
            ]
          },
          {
            label: '是否启用',
            prop: 'isEnabled',
            type: 'switch',
            dicData: [
              {
                label: '否',
                value: false
              },
              {
                label: '是',
                value: true
              }
            ]
          },
          {
            label: '开始日期',
            prop: 'planStartTime'
          },
          {
            label: '结束日期',
            prop: 'planEndTime'
          },
          {
            label: '创建时间',
            prop: 'createTime'
          }
        ]
      };
    },
    openAreaStash() {
      // this.selectAreaDialog = true;
      this.modalName = 'stash';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '指定仓库（双击进行选择）',
        url: '/api/mes-admin/area/page/storage/management?parentId=0',
        isPage: true,
        rowSelectionType: 'multiple',
        searchMenuSpan: 4,
        isHaveRowKey: 'no',
        index: true,
        indexLabel: '序号',
        rowKey: 'keyJson',
        columnDefs: [
          {
            label: '仓库',
            prop: 'code',
            search: true,
            hide: true,
            searchOrder: 1,
            type: 'select',
            dicData: [],
            props: {
              label: 'name',
              value: 'code'
            }
          },
          {
            label: '仓库编码',
            prop: 'code'
          },
          {
            label: '仓库名称',
            prop: 'name',
            search: true
          }
        ]
      };
      this.getInventoryInfois();
    },
    getInventoryInfois() {
      const column = this.findObject(this.tableOption.columnDefs, 'code');
      column.dicData = [];
      getInventoryInfo('1', '999', { parentId: '0' }).then((res) => {
        let data = res.data.data.records || [];
        column.dicData = data;
      });
    },
    openAreaSelect() {
      // this.selectAreaDialog = true;

      this.modalName = 'region';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '指定区域（双击进行选择）',
        url: '/api/mes-admin/area/page/storage/management?areaType=STORAGE_AREA',
        isPage: true,
        rowSelectionType: 'multiple',
        searchMenuSpan: 4,
        isHaveRowKey: 'no',
        rowKey: 'keyJson',
        index: true,
        indexLabel: '序号',
        columnDefs: [
          {
            label: '区域编码',
            prop: 'code',
            search: true,
            searchOrder: 3
          },
          // {
          //   label: '区域',
          //   prop: 'parentId',
          //   search: true,
          //   searchOrder: 2,
          //   type: 'select',
          //   hide: true,
          //   dicFlag: false,
          //   dicUrl: '/api/mes-admin/area/select/storage/management?parentId={{key}}',
          //   props: {
          //     label: 'name',
          //     value: 'id'
          //   }
          // },
          {
            label: '区域名称',
            prop: 'name',
            search: true
          },
          {
            label: '所属仓库',
            prop: 'inventoryName'
          },
          {
            label: '所属仓库',
            prop: 'inventoryId',
            search: true,
            hide: true,
            searchOrder: 1,
            type: 'select',
            dicData: [],
            props: {
              label: 'name',
              value: 'id'
            },
            cascader: ['parentId'],
            change: (val) => {
              if (val.value) {
                this.getSubTypeList(val.value);
              }
            }
          },
          {
            label: '等级',
            prop: 'level',
            type: 'select',
            search: true,
            dicData: [],
            searchOrder: 2,
            props: {
              label: 'name',
              value: 'id'
            },
            hide: true
          }
        ]
      };
      this.getInventoryInfo();
    },
    getInventoryInfo() {
      const column = this.findObject(this.tableOption.columnDefs, 'inventoryId');
      column.dicData = [];
      getInventoryInfo('1', '999', { parentId: '0' }).then((res) => {
        let data = res.data.data.records || [];
        column.dicData = data;
      });
    },
    getSubTypeList(data) {
      const column = this.findObject(this.tableOption.columnDefs, 'level');
      column.dicData = [];
      getSubTypeList({ inventoryId: data }).then((res) => {
        let data = res.data.data || [];
        let levelList = [];
        for (let i = data + 1; i--; ) {
          if (i == 1) {
            break;
          }
          levelList.push({ name: i, id: i });
        }
        console.log(levelList, 'levelList');
        column.dicData = levelList;
      });
    },
    saveArea() {
      if (this.selectAreaList.length === 0) {
        this.$message({
          type: 'warning',
          message: '请选择区域！'
        });
        return;
      }
      this.savaAreaLoading = true;
      getPartByArea(this.selectAreaList).then(
        (res) => {
          this.selectAreaDialog = false;
          if (res.data.data && res.data.data.length > 0) {
            this._forEach(res.data.data, (item) => {
              item.keyJson = JSON.stringify(item);
            });
            if (this.partList.length > 0) {
              this._forEach(res.data.data, (item) => {
                let obj = this._find(this.partList, { inventoryId: item.inventoryId, areaId: item.areaId, partNo: item.partNo, lotNo: item.lotNo });
                if (obj) {
                  let index = this.partList.indexOf(obj);
                  this.partList[index] = item;
                } else {
                  this.partList.push(item);
                }
              });
            } else {
              this.partList = res.data.data;
            }
          }
          this.savaAreaLoading = false;
        },
        (error) => {
          this.savaAreaLoading = false;
        }
      );
    },
    closeAreaDialog() {
      this.areaList = [];
      this.selectAreaList = [];
    },
    openPartSelect() {
      this.modalName = 'partModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择产品信息（双击进行选择）',
        url: '/api/mes-warehouse/packing/query-material-page',
        isPage: true,
        rowSelectionType: 'multiple',
        searchMenuSpan: 4,
        isHaveRowKey: 'no',
        rowKey: 'keyJson',
        columnDefs: [
          {
            label: '编码',
            prop: 'partNo',
            search: true
          },
          {
            label: '名称',
            prop: 'partMasterName',
            search: true
          },
          {
            label: '型号',
            prop: 'partModel'
          },
          {
            label: '类型',
            prop: 'partType',
            search: true,
            type: 'select',
            dicData: [
              { label: '成品', value: 'PRODUCT' },
              { label: '原料', value: 'MATERIAL' }
            ]
          },
          {
            label: '物料批次',
            prop: 'lotNo'
          },
          {
            label: '库存数量',
            prop: 'inventoryQuantity'
          }
        ]
      };
    },
    /**
     * 获取选择的模态框行数据
     */
    getSelectedRows(rowData) {
      switch (this.modalName) {
        case 'principalModal':
          let operators = [];
          this._forEach(rowData, (item) => {
            operators.push({ id: item.id, realName: item.realName });
          });
          this.form.operators = JSON.stringify(operators);
          let operatorsName = [];
          this._forEach(rowData, (item) => {
            operatorsName.push(this._get(item, 'realName', ''));
          });
          this.form.operatorsName = operatorsName.join(',');
          break;
        case 'referencePlanNoModal':
          this.form.referencePlanNo = this._get(rowData, 'planNo', '');
          break;
        case 'region':
          this.selectAreaList = rowData;
          this.saveArea();
          break;
        case 'stash':
          this.selectAreaList = rowData;
          this.saveArea();
          break;
        case 'partModal':
          if (this.partList.length > 0) {
            this._forEach(rowData, (item) => {
              let obj = this._find(this.partList, { inventoryId: item.inventoryId, areaId: item.areaId, partNo: item.partNo, lotNo: item.lotNo });
              if (obj) {
                let index = this.partList.indexOf(obj);
                this.partList[index] = item;
              } else {
                this.partList.push(item);
              }
            });
          } else {
            this.partList = rowData;
          }
      }
    },
    selectionPartChange(list) {
      this.selectionPartList = list;
    },
    deletePart() {
      if (this.selectionPartList.length < 1) {
        this.$message({
          type: 'warning',
          message: '至少选择一条物料！'
        });
        return;
      }
      // this._forEach(this.partList, (item, index) => {
      this._forEach(this.selectionPartList, (selectItem) => {
        let index = this.partList.indexOf(selectItem);
        // if (item.keyJson === selectItem.keyJson) {
        this.partList.splice(index, 1);
        // }
      });
      // });
    },
    complete(row, btnType) {
      this.$confirm('是否确定完成这条数据?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        checkCompleted(row.id).then(
          () => {
            this.onLoad(this.page);
            this.$message({
              type: 'success',
              message: '已完成!'
            });
          },
          (error) => {}
        );
      });
    },
    /**
     * 提交
     */
    submit() {
      this.$refs.basicInfo.validate((valid, done) => {
        if (valid) {
          if (this.partList.length < 1) {
            this.$message({
              type: 'warning',
              message: '物料盘点列表不能为空！'
            });
            done();
          } else {
            this._forEach(this.partList, (item) => {
              delete item.keyJson;
            });
            this.form.planStartTime = this.form.checkDate[0];
            this.form.planEndTime = this.form.checkDate[1];
            this.form.checkingMaterial = this.partList;
            this.planSaveLoading = true;
            add(this.form).then(
              (res) => {
                this.onLoad(this.page);
                this.$message({
                  type: 'success',
                  message: res.data.msg
                });
                this.showDialog = false;
                this.planSaveLoading = false;
              },
              (error) => {
                this.planSaveLoading = false;
              }
            );
            done();
          }
        }
      });
    },
    /**
     * 查看详情数据
     */
    rowView(row) {
      this.showDialog = true;
      this.dialogTitle = '详情';
      this.$nextTick(() => {
        this.$refs.basicInfo.allDisabled = true;
      });
      this.form = row;
      this.form.checkDate = [row.planStartTime, row.planEndTime];
      let operatorsName = [];
      this._forEach(JSON.parse(this.form.operators), (item) => {
        operatorsName.push(item.realName);
      });
      this.form.operatorsName = operatorsName.join(',');
      this.checkMaterialLoading = true;
      getCheckMaterialPage(this.page.currentPage, this.page.pageSize, { planId: row.id }).then((res) => {
        const data = res.data.data;
        this.checkMaterialPage.total = data.total;
        this.checkMaterialList = data.records;
        this.checkMaterialLoading = false;
      });
    },
    rowUpdate(row) {
      this.showDialog = true;
      this.dialogTitle = '编辑';
      this.$nextTick(() => {
        this.$refs.basicInfo.allDisabled = false;
      });
      this.form = row;
      this.form.checkDate = [row.planStartTime, row.planEndTime];
      let operatorsName = [];
      this._forEach(JSON.parse(this.form.operators), (item) => {
        operatorsName.push(item.realName);
      });
      this.form.operatorsName = operatorsName.join(',');
      getCheckMaterialList(row.id).then((res) => {
        this.partList = res.data.data;
        this._forEach(this.partList, (item) => {
          item.keyJson = JSON.stringify(item);
        });
      });
    },
    closeDialog() {
      this.$refs.basicInfo.resetFields();
      this.form = {};
      this.partList = [];
    },
    cancel() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据取消?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return checkCancel(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    },
    viewPackInfo(row) {
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '查看包装',
        url: `/api/mes-warehouse/checking/checking-material/page?planId=${this.form.id}&checkingAreaId=${row.checkingAreaId}&lotNo=${row.lotNo}&partNo=${row.partNo}&partModel=${row.partModel}&partType=${row.partType}`,
        isPage: true,
        rowSelectionType: 'single',
        readonly: true,
        columnDefs: [
          {
            label: '包装条码',
            prop: 'packNo'
          },
          {
            label: '账面数量',
            prop: 'inventoryQuantity'
          },
          {
            label: '实盘数量',
            prop: 'checkQuantity'
          },
          {
            label: '盈亏数量',
            prop: 'difference',
            html: true,
            formatter: (val) => {
              if (Number(val.difference) < 0) {
                return '<span class="text-green">' + val.difference + '</span>';
              } else if (Number(val.difference) > 0) {
                return '<span class="text-red">' + val.difference + '</span>';
              } else {
                return val.difference;
              }
            }
          },
          {
            label: '状态',
            prop: 'status',
            type: 'select',
            dicUrl: '/api/blade-system/dict/dictionary?code=check_status',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            formatter: (val) => {
              switch (val.status) {
                case 1:
                  return '待执行';
                case 2:
                  return '盘点中';
                case 3:
                  return '待审核';
                case 4:
                  return '已审核';
                case 5:
                  return '已取消';
              }
            }
          },
          {
            label: '库存中心',
            prop: 'inventoryName'
          },
          {
            label: '储位编码',
            prop: 'areaCode'
          },
          {
            label: '储位名称',
            prop: 'areaName'
          },
          {
            label: '备注',
            prop: 'remark'
          }
        ]
      };
    },
    enable() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据启用?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return checkEnable(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    },
    /**
     * 获取打印机和打印模版信息
     */
    getPrintInfo(printInfo) {
      if (printInfo.printersId) {
        this.printInfo.printersId = printInfo.printersId;
      }
      if (printInfo.labelTemplateId) {
        this.printInfo.labelTemplateId = printInfo.labelTemplateId;
      }
    },
    showPrint(row) {
      this.printDialog = true;
      this.selectPrintPlanId = row.id;
    },
    submitPrint() {
      if (!this.printInfo.printersId) {
        this.$message({
          type: 'warning',
          message: '请选择打印机！'
        });
        return;
      }
      if (!this.printInfo.labelTemplateId) {
        this.$message({
          type: 'warning',
          message: '请选择标签模版！'
        });
        return;
      }
      let params = {
        ids: this.selectPrintPlanId,
        equipmentId: this.printInfo.printersId,
        labelTemplateId: this.printInfo.labelTemplateId
      };
      this.savePrintLoading = true;
      checkPrint(params).then(
        (res) => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '打印成功!'
          });
          this.printDialog = false;
          this.savePrintLoading = false;
        },
        (error) => {
          this.savePrintLoading = false;
        }
      );
    },
    closePrintDialog() {
      this.$refs.printInfo.reset();
      this.printInfo = {};
    }
  }
};
</script>
<style lang="scss" scoped>
.inventoryDialog {
  ::v-deep .avue-crud__menu {
    display: none;
  }
  h3 {
    font-size: 16px;
  }
  .mr10 {
    margin-right: 10px;
  }
}
::v-deep .el-range-editor.is-disabled input {
  color: #606266 !important;
}
</style>
